﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Data.OleDb;
using System.Diagnostics;
using KEW.InterFace;

namespace AutoGam
{
    public partial class MainForm : Form
    {
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            PanelPassWordPad.BringToFront();
            try
            {
                int processCount = 0;
                Process[] pa = Process.GetProcesses();//获取当前进程数组。  
                foreach (Process PTest in pa)
                {
                    if (PTest.ProcessName == Process.GetCurrentProcess().ProcessName)
                    {
                        processCount += 1;
                    }
                }
                if (processCount > 1)
                {
                    MessageBox.Show("程序已经在运行！");
                    this.Close();
                    return;
                }

                LoadBaseInfo();
                Device.Init();
                if (!Device.UsbCardDevice.Enable)
                {
                    MessageBox.Show("USB读卡器加载失败");
                }
                if (!Program.IsDebug)
                {
                    FormMax();
                }

                MainTimer.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //this.Close();
            }
        }

        private void FormMax()
        {
            this.TopMost = true;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
            ShowCursor(0);
        }

        private void FormMin()
        {
            this.TopMost = false;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
            this.WindowState = FormWindowState.Normal;
            ShowCursor(1);
        }

        [DllImport("user32.dll", EntryPoint = "ShowCursor", CharSet = CharSet.Auto)]
        private static extern void ShowCursor(int status);

        private void ButtonSales1_Click(object sender, EventArgs e)
        {
            SalesForm sf = new SalesForm();
            Device.ButtonVoice();
            AllowOpen = false;
            sf.ShowDialog();
            AllowOpen = true;
        }

        private void MainForm_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Back:
                    FormMin();
                    break;
                case Keys.Escape:
                    FormMin();
                    break;
            }
        }

        private void LoadBaseInfo()
        {
            try
            {
                OleDbConnection App_Con = new OleDbConnection();
                App_Con.ConnectionString = String.Format("File Name={0}\\Data.udl", System.Environment.CurrentDirectory);
                App_Con.Open();
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = App_Con;
                cmd.CommandText = "SELECT A.FText BaseName,A.FText1 IPAdd,A.FText2 DataUser,A.FText3 DataPswd,A.FNumber,A.FName,A.FID FROM KEW_DataBaseEntry A";
                OleDbDataReader reader = cmd.ExecuteReader();
                Program.DataConnString.Clear();
                while (reader.Read())
                {
                    String connection = String.Format("Provider=SQLOLEDB;Data Source={0};Initial Catalog={1};User ID={2};Password={3};Connect Timeout=15",
                        reader["IPAdd"].ToString(), reader["BaseName"].ToString(), reader["DataUser"].ToString(), reader["DataPswd"].ToString());
                    Program.DataConnString.Add(reader["FNumber"].ToString(), connection);
                }

                if (App_Con.State == ConnectionState.Open)
                {
                    App_Con.Close();
                }
                App_Con.Dispose();
                cmd.Dispose();
                reader.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            ButtonSales1.Location = new Point((this.Size.Width - ButtonSales1.Size.Width) / 2, ButtonSales1.Location.Y);
            ButtonSales2.Location = new Point((this.Size.Width - ButtonSales2.Size.Width) / 2, ButtonSales2.Location.Y);
            ButtonPurch1.Location = new Point((this.Size.Width - ButtonPurch1.Size.Width) / 2, ButtonPurch1.Location.Y);
            LabNote1.Location = new Point((this.Size.Width - LabNote1.Size.Width) / 2, LabNote1.Location.Y);
            LabNote2.Location = new Point((this.Size.Width - LabNote2.Size.Width) / 2, LabNote2.Location.Y);
            PanelLoading.Location = new Point(0, PanelLoading.Location.Y);
            PanelLoading.Width = this.Width;
            PbLoading.Location = new Point((this.Size.Width - PbLoading.Size.Width) / 2, PbLoading.Location.Y);
            label1.Location = new Point((this.Size.Width - label1.Size.Width) / 2, label1.Location.Y);
            label2.Location = new Point((this.Size.Width - label2.Size.Width) / 2, label2.Location.Y);
        }

        private void ButtonPurch1_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            PurchForm pf = new PurchForm();
            AllowOpen = false;
            pf.ShowDialog();
            AllowOpen = true;
        }

        private void PageSales_Num1_Click(object sender, EventArgs e)
        {
            TxtPassWord.Text += ((Button)sender).Text;
        }

        private void ButtonClear_Click(object sender, EventArgs e)
        {
            TxtPassWord.Text = String.Empty;
        }

        private void ButtonOK_Click(object sender, EventArgs e)
        {
            if (TxtPassWord.Text == "3317975")
            {
                PanelFunctionButton.Visible = true;
            }
        }

        private void ButtonCloseForm_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ButtonCardIn_Click(object sender, EventArgs e)
        {
            Device.GetCard();
        }

        private void ButtonOut_Click(object sender, EventArgs e)
        {
            Device.SendCard();
        }

        private void ButtonRevice_Click(object sender, EventArgs e)
        {
            Device.ReviceCard();
        }

        private void LabErrorMessage_Click(object sender, EventArgs e)
        {
            PanelPassWordPad.Visible = false;
            PanelFunctionButton.Visible = false;
        }

        private void LabManager_DoubleClick(object sender, EventArgs e)
        {
            TxtPassWord.Text = String.Empty;
            PanelPassWordPad.Visible = true;
        }

        private void ButtonUsb_Click(object sender, EventArgs e)
        {
            UsbCardForm scf = new UsbCardForm();
            scf.ShowDialog();
        }

        private void ButtonCom_Click(object sender, EventArgs e)
        {
            ComCardForm ccf = new ComCardForm();
            ccf.ShowDialog();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Device.Exit();
        }

        private void ButtonSales2_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            ShippingForm sp = new ShippingForm();
            AllowOpen = false;
            sp.ShowDialog();
            AllowOpen = true;
        }

        private void MainTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (AllowOpen && !Program.IsDebug && !PanelPassWordPad.Visible)
                {
                    String currSerial = Device.ComCardDevice.GetSerial();
                    if (currSerial != "")
                    {
                        if (UseSerial == "")
                        {
                            UseSerial = currSerial;
                            Device.ComCardDevice.Beep();
                            PanelLoading.Visible = true;
                            Application.DoEvents();
                            String bock32 = Device.ComCardDevice.ReadBlock(KEW.InterFace.Block.Block32);
                            String bock33 = Device.ComCardDevice.ReadBlock(KEW.InterFace.Block.Block33);
                            String bock34 = Device.ComCardDevice.ReadBlock(KEW.InterFace.Block.Block34);
                            String bock36 = Device.ComCardDevice.ReadBlock(KEW.InterFace.Block.Block36);
                            String bock37 = Device.ComCardDevice.ReadBlock(KEW.InterFace.Block.Block37);
                            String bock38 = Device.ComCardDevice.ReadBlock(KEW.InterFace.Block.Block38);
                            String bock40 = Device.ComCardDevice.ReadBlock(KEW.InterFace.Block.Block40);
                            PanelLoading.Visible = false;
                            Application.DoEvents();
                            switch (bock32)
                            {
                                case "销售提货":
                                    Device.ButtonVoice();
                                    SalesPswd sp = new SalesPswd();
                                    sp.PageSales_NumText.Text = bock33; //编号
                                    sp.PageCar_Text.Text = bock36; //车牌号
                                    sp.PageSales_PreQty.Text = Common.Qty(bock37).ToString();
                                    sp.PreItem = bock38;
                                    sp.isPswdInputFocus = true;
                                    sp.CardSerial = UseSerial;
                                    sp.CardNo = bock34;
                                    sp.BaseName = bock40;
                                    AllowOpen = false;
                                    sp.ShowDialog();
                                    AllowOpen = true;
                                    break;
                                case "采购供货":
                                    Device.ButtonVoice();
                                    PurchForm pf = new PurchForm();
                                    pf.PageSales_NumText.Text = bock33; //编号
                                    pf.PageCar_Text.Text = bock36; //车牌号
                                    pf.CardSerial = UseSerial;
                                    pf.CardNo = bock34;
                                    pf.BaseName = bock40;
                                    AllowOpen = false;
                                    pf.ShowDialog();
                                    AllowOpen = true;
                                    break;
                            }
                        }
                    }
                    else
                    {
                        UseSerial = "";
                    }
                }
            }
            catch (Exception) {
                PanelLoading.Visible = false;
            }
        }

        private string UseSerial = "";
        private Boolean AllowOpen = true;
    }
}
